#include <rtc_base/logging.h>
#include <errno.h>
#include <netinet/in.h>
#include <ifaddrs.h>
#include "base/network.h"
namespace xrtc
{

    NetworkManager::NetworkManager() = default;
    NetworkManager::~NetworkManager()
    {

        for (auto network : network_list_)
        {
            delete network;
        }
        network_list_.clear();
    }

    int NetworkManager::CreateNetworks()
    {
        // 获取本机的网络接口
        struct ifaddrs *interface;
        int err = getifaddrs(&interface);
        if (err != 0)
        {
            RTC_LOG(LS_WARNING) << "getifaddrs error:" << strerror(errno)
                                << ", errno : " << errno;
            return -1;
        }
        // 遍历网卡信息
        for (auto cur = interface; cur != nullptr; cur = cur->ifa_next)
        {
            if (cur->ifa_addr->sa_family != AF_INET)
            {
                continue;
            }
            struct sockaddr_in *addr = (struct sockaddr_in *)(cur->ifa_addr);
            rtc::IPAddress ip_address((addr->sin_addr));
            // 过滤局域网的网卡，我们环境搭建在局域网上，所以不需要这一行，如果我们的服务器搭建在公网上，需要加上这一行，通过公网给外部通信，这里我们把它注释掉
            //  if(rtc::IPIsPrivateNetwork(ip_address)) {
            //      continue;
            //  }
            if (rtc::IPIsLoopback(ip_address))
            {
                continue;
            }
            Network *network = new Network(cur->ifa_name, ip_address);

            RTC_LOG(LS_INFO) << "gathered network interface:" << network->ToString();
            network_list_.push_back(network);
        }

        freeifaddrs(interface);

        return 0;
    }

}